package com.liusu.file.controller;

import com.liusu.common.annotation.Anonymous;
import com.liusu.common.core.domain.AjaxResult;
import com.liusu.common.utils.StringUtils;
import com.liusu.common.utils.file.FileUtils;
import com.liusu.file.dto.CompleteMultipartUploadRequest;
import com.liusu.file.dto.MultipartUploadCreateRequest;
import com.liusu.file.dto.MultipartUploadCreateResponse;
import com.liusu.file.dto.UploadPartRequest;
import com.liusu.file.utils.MinioUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/minio/file")
@Anonymous
public class MinioFileController {
    private static final Logger log = LoggerFactory.getLogger(MinioFileController.class);


    @Autowired
    private MinioUtil minioUtil;

    /**
     * 通用下载请求
     *
     * @param fileName 文件路径名称
     * @param delete   是否删除
     */
    @GetMapping("/download")
    public void fileDownload(@RequestParam("fileName") String fileName,
                             @RequestParam(value = "delete", required = false, defaultValue = "false") Boolean delete,
                             HttpServletResponse response,
                             HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            minioUtil.download(fileName, response);
            if (delete) {
                minioUtil.remove(fileName);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) {
        try {
            String fileName = minioUtil.upload(file);

            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", minioUtil.getObjectUrl(fileName));
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files) {
        try {
            List<String> urls = new ArrayList<>();
            List<String> fileNames = new ArrayList<>();
            List<String> newFileNames = new ArrayList<>();
            List<String> originalFilenames = new ArrayList<>();
            for (MultipartFile file : files) {
                AjaxResult result = uploadFile(file);

                urls.add(result.get("url").toString());
                fileNames.add(result.get("fileName").toString());
                newFileNames.add(result.get("newFileName").toString());
                originalFilenames.add(result.get("originalFilename").toString());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FileUtils.FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FileUtils.FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FileUtils.FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FileUtils.FILE_DELIMETER));
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 1.分片上传初始化
     *
     * @param request 分片上传请求
     * @return 初始化结果，主要是上传的ID
     */
    @PostMapping("/multipart/create")
    public AjaxResult createMultipartUpload(@RequestBody @Validated MultipartUploadCreateRequest request) {
        if (FileUtils.file_KbToMb(request.getFileSize()) < FileUtils.SIZE_MB * 5) {
            return AjaxResult.error("文件大小不符合要求，分片要求最小为5Mb");
        }
        MultipartUploadCreateResponse response = minioUtil.createMultipartUpload(request);
        return AjaxResult.success(response);
    }

    /**
     * 2.上传分片数据
     *
     * @param request 分片数据
     * @return 结果标识
     */
    @PutMapping(value = "/multipart/upload")
    public AjaxResult uploadPart(UploadPartRequest request) {
        minioUtil.uploadPart(request);
        return AjaxResult.success();
    }

    /**
     * 3.合并分片
     *
     * @param request 合并请求
     * @return 合并结果，包含上传后的文件地址
     */
    @PostMapping("/multipart/complete")
    public AjaxResult completeMultipartUpload(@RequestBody @Validated CompleteMultipartUploadRequest request) {
        String fileName = minioUtil.completeMultipartUpload(request);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("url", minioUtil.getObjectUrl(fileName));
        ajax.put("fileName", fileName);
        ajax.put("newFileName", FileUtils.getName(fileName));
        ajax.put("originalFilename", request.getOriginalFilename());
        return ajax;
    }
}
